/**
 * Created by Administrator on 2018/12/31.
 */
package com.game.fg.service;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.concurrent.Callable;

public class DBPool {

    @Autowired
    private DruidDataSource druidDataSource;

    private static Logger logger = LogManager.getLogger(DBPool.class.getName());
    //建立连接的驱动驱动名称
    private static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
    //最大空闲链接
    private static final int MAX_IDLE = 20;
    //最大空闲连接
    private static final int MinIdle = 8;
    //初始化时链接池的数量
    static final int INITIAL_SIZE = 20;
    //一个被抛弃连接可以被移除的超时时间
    private static final int RemoveAbandonedTimeout = 180;
    //只会发现当前连接失效，再创建一个连接供当前查询使用
    private static final boolean TOBESTNORROW = true;
    //private static BasicDataSource DATA_SOURCE;

    public  Connection getConnection () throws SQLException{
        return druidDataSource.getConnection();
    }



    //提供获得数据源
    /*static DataSource getDateSource() {
        return DATA_SOURCE;
    }*/

    //提供获得链接
    /*public static Connection getConnection() throws SQLException {
        return DATA_SOURCE.getConnection();
    }*/

    //线程中执行sql
    static void executeInThread(Object sqlCommand, String prepareSql) {
        SqlCommand task;
        if (StringUtils.isEmpty(prepareSql)) {
            task = new SqlCommand(sqlCommand);
        } else {
            task = new SqlCommand(sqlCommand, prepareSql);
        }
        FGMain.executorForMysql.submit(task);
    }

    private static int logCount = 0;

    //SQL
    public static class SqlCommand implements Callable {
        private Object sqlCommand;
        private String prepareSql;

        SqlCommand(Object sqlCommand) {
            this.sqlCommand = sqlCommand;
        }

        SqlCommand(Object sqlCommand, String prepareSql) {
            this.sqlCommand = sqlCommand;
            this.prepareSql = prepareSql;
        }

        @SuppressWarnings("unchecked")
        public String call() throws Exception {
            String sql = "";
            try {
                DBPool dbPool=new DBPool();
                Connection conn = dbPool.getConnection();
                if (sqlCommand instanceof String) {
                    sql = sqlCommand.toString();
                    Statement s = conn.createStatement();
                    s.execute(sqlCommand.toString());
                    s.close();
                } else if (sqlCommand instanceof java.util.List) {
                    PreparedStatement pStatement = conn.prepareStatement(prepareSql);
                    for (FGGame.GameLog gl : (ArrayList<FGGame.GameLog>) sqlCommand) {
                        pStatement.setInt(1, gl.uid);
                        pStatement.setInt(2, gl.round);
                        pStatement.setInt(3, gl.result);
                        pStatement.setInt(4, gl.changeMoney);
                        pStatement.setInt(5, gl.leftMoney);
                        pStatement.setFloat(6, (float) gl.taxRate);
                        pStatement.setString(7, gl.des);
                        pStatement.setInt(8, (int) gl.time);
                        pStatement.addBatch();
                        DBPool.logCount += 1;
                    }
                    //TODO:测试入库性能
                    //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //System.out.println(String.format("================   %s  %d %d", df.format(System.currentTimeMillis()), FGTimer.gotCount, DBPool.logCount));
                    pStatement.executeBatch();
                    pStatement.close();
                }
                conn.close();
            } catch (SQLException e) {
                logger.error("mysql错误:" + sql, e);
                return "Failed";
            }
            return "Success";
        }
    }

}
